package cn.mrdjun.redis.stater.ratelimiter;

import cn.mrdjun.redis.stater.properties.RateLimitProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 限流配置
 *
 * @author DengJun 2021/3/23
 */
@Configuration
@RequiredArgsConstructor
@ConditionalOnWebApplication
@EnableConfigurationProperties({RateLimitProperties.class})
@ConditionalOnProperty(value = "fun.redis.limit.enable", havingValue = "true")
public class RateLimitInterceptorConfigure implements WebMvcConfigurer {
    private final RateLimitProperties properties;
    private final RedisTemplate<String, Object> redisTemplate;

    @Bean
    public IpRateLimitAspect ipRateLimitAspect() {
        return new IpRateLimitAspect(redisTemplate);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new RateLimiterInterceptor(redisTemplate)).addPathPatterns(properties.getPath());
    }
}
